package com.software.loginregister.activity;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.software.loginregister.R;
import com.software.loginregister.adapter.FoodAdapter;
import com.software.loginregister.api.AiServiceApi;
import com.software.loginregister.entity.ChatResponse;
import com.software.loginregister.entity.FoodItem;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.vo.FoodRecognitionDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ResultActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private FoodAdapter adapter;
    private Button btnAddToFridge;
    private String uploadFileId;
    private Long imageId;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        // 初始化视图
        initViews();
        setupRecyclerView();
        setupSwipeRefresh();

        // 获取上传的文件ID并开始分析
        uploadFileId = getIntent().getStringExtra("uploadFileId");
        imageId = Long.valueOf(getIntent().getStringExtra("imageId")); // 获取imageId
        adapter.setImageId(imageId);
        Log.d("AddToFridge","imageID"+imageId);
        if (uploadFileId != null) {
            analyzeImage();
        } else {
            Toast.makeText(this, "未获取到图片信息", Toast.LENGTH_SHORT).show();
            finish();
        }

        setStatusBar();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        btnAddToFridge = findViewById(R.id.result_btn_AddToFridge);
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在识别...");
        progressDialog.setCancelable(false);

        btnAddToFridge.setOnClickListener(v -> addFoodsToFridge());
    }

    private void addFoodsToFridge() {
        Long userId = SharedPreferencesUtil.getUserId(this);
        if (userId == null) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            return;
        }



        // 显示加载对话框
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在添加到冰箱...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        // 获取适配器中的食材列表
        List<FoodRecognitionDTO> foods = adapter.getFoodRecognitionList();
        if (foods == null || foods.isEmpty()) {
            Toast.makeText(this, "没有可添加的食材", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
            return;
        }

        // 添加日志
        Log.d("AddToFridge", "Sending request - userId: " + userId + ", foods: " + foods.size());

        RetrofitClient.getInstance()
                .getRefrigeratorApi()
                .addFoodsToFridge(userId, foods)
                .enqueue(new Callback<Result<String>>() {
                    @Override
                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                        progressDialog.dismiss();

                        // 添加详细的日志
                        Log.d("AddToFridge", "Response code: " + response.code());
                        Log.d("AddToFridge", "Response successful: " + response.isSuccessful());
                        Log.d("AddToFridge", "Response body: " + (response.body() != null ? response.body().toString() : "null"));

                        if (!response.isSuccessful()) {
                            try {
                                String errorBody = response.errorBody() != null ?
                                        response.errorBody().string() : "Unknown error";
                                Log.e("AddToFridge", "Error body: " + errorBody);
                                Toast.makeText(ResultActivity.this,
                                        "请求失败: " + response.code() + " - " + errorBody,
                                        Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                Log.e("AddToFridge", "Error reading error body", e);
                                Toast.makeText(ResultActivity.this,
                                        "请求失败: " + response.code(),
                                        Toast.LENGTH_SHORT).show();
                            }
                            return;
                        }

                        Result<String> result = response.body();
                        if (result == null) {
                            Toast.makeText(ResultActivity.this,
                                    "服务器响应为空",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }

                        Log.d("AddToFridge", "Result code: " + result.getCode());
                        Log.d("AddToFridge", "Result message: " + result.getMsg());

                        if (result.getCode() == 1) {
                            Toast.makeText(ResultActivity.this,
                                    "已成功添加到冰箱",
                                    Toast.LENGTH_SHORT).show();
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            String errorMsg = result.getMsg();
                            if (errorMsg == null || errorMsg.isEmpty()) {
                                errorMsg = "添加失败";
                            }
                            Toast.makeText(ResultActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable t) {
                        progressDialog.dismiss();
                        Log.e("AddToFridge", "Network error", t);
                        Toast.makeText(ResultActivity.this,
                                "网络错误: " + t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new FoodAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    private void setupSwipeRefresh() {
        swipeRefreshLayout.setColorSchemeResources(
                R.color.theme_color
        );

        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 重新分析图片
            if (uploadFileId != null) {
                analyzeImage();
            } else {
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(this, "无法刷新，图片ID丢失", Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private void analyzeImage() {
        // 如果是下拉刷新触发的，就不显示进度对话框
        if (!swipeRefreshLayout.isRefreshing()) {
            progressDialog.show();
        }

        Long userId = SharedPreferencesUtil.getUserId(this);
        if (userId == null) {
            Toast.makeText(this, "用户未登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        AiServiceApi aiService = RetrofitClient.getInstance().create(AiServiceApi.class);
        aiService.chatWithImage(
                String.valueOf(userId),
                uploadFileId,
                "请识别图片中的食材",
                "app1"  // 添加默认的appId参数
        ).enqueue(new Callback<ChatResponse>() {
            @Override
            public void onResponse(Call<ChatResponse> call, Response<ChatResponse> response) {
                // 无论是进度对话框还是下拉刷新的加载动画，都需要关闭
                progressDialog.dismiss();
                swipeRefreshLayout.setRefreshing(false);

                if (response.isSuccessful() && response.body() != null) {
                    handleSuccessResponse(response.body());
                } else {
                    showError("请求失败: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<ChatResponse> call, Throwable t) {
                progressDialog.dismiss();
                swipeRefreshLayout.setRefreshing(false);
                showError("网络错误: " + t.getMessage());
            }
        });
    }

    private void handleSuccessResponse(ChatResponse chatResponse) {
        if ("success".equals(chatResponse.getStatus())) {
            try {
                List<FoodRecognitionDTO> foods = chatResponse.getFoods();
                if (foods != null && !foods.isEmpty()) {
                    // 将 FoodRecognitionDTO 转换为 FoodItem
                    List<FoodItem> foodList = new ArrayList<>();
                    for (FoodRecognitionDTO food : foods) {
                        FoodItem foodItem = new FoodItem();
                        foodItem.setName(food.getName());
                        foodItem.setQuantity(food.getQuantity());
                        foodItem.setUnit(food.getUnit());
                        foodItem.setStorage(food.getStorage());
                        foodItem.setDays(food.getDays());
                        foodList.add(foodItem);
                    }

                    runOnUiThread(() -> {
                        adapter.setFoodList(foodList);
                        Log.d("Food Recognition", "识别到 " + foodList.size() + " 个食材");
                    });
                } else {
                    showError("未识别到食材信息");
                    Log.w("Food Recognition", "食材列表为空");
                }
            } catch (Exception e) {
                e.printStackTrace();
                showError("处理识别结果失败: " + e.getMessage());
                Log.e("Food Recognition", "处理失败", e);
            }
        } else {
            showError(chatResponse.getErrorMessage());
            Log.e("Food Recognition", "识别失败: " + chatResponse.getErrorMessage());
        }
    }

    private void showError(String message) {
        runOnUiThread(() -> {
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
        });
    }
}